import { v4 } from 'uuid'
import dayjs from 'dayjs'
import { useUserStore } from '@/store/useUserStore'
import { getUrlParams } from '@/utils/util'

export function useChatStore() {
  const { shareId } = getUrlParams(location.href)
  // 本地存储(对话相关)
  function chatStore() {
    const userStore = useUserStore()
    const userId = userStore.userInfo?.id || 'pre_ncloud_sys_user_10000'

    // 区分session
    const key = shareId ? 'share-list-store-' + shareId : 'appChat-list-store-' + userId
    // 获取本地存储
    function getStore() {
      let store = localStorage.getItem(key)
      let dx = null
      if (store === null) {
        dx = {
          sessions: [],
        }
        localStorage.setItem(key, JSON.stringify(dx))
      } else {
        dx = JSON.parse(store)
      }
      return dx
    }

    // 设置本地存储
    function setStore(data) {
      localStorage.setItem(key, JSON.stringify(data))
    }

    // 获取本地存储中的sessions
    function getSessions() {
      const store = getStore()
      return store.sessions
    }

    // 保存sessions到本地存储
    function saveSessions(sessions) {
      setStore({ sessions })
    }

    // 创建session（保存至本地存储）
    function createSession(appId = '') {
      const sessions = getSessions()
      const session = {
        id: v4().replaceAll('-', ''),
        appId: appId,
        title: '新的对话',
        messages: [],
        createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      }
      sessions.unshift(session)
      setStore({ sessions })
      return session
    }

    return {
      getSessions,
      saveSessions,
      createSession,
    }
  }

  return {
    chatStore,
  }
}
